package com.ikingtech.platform.service.authentication.converter;

import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.platform.service.authentication.web.AuthenticationRequest;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.util.MultiValueMap;

/**
 * @author tie yan
 */
public class AuthorizationCodeRequestConverter implements AuthenticateConverter{

    @Override
    public AuthenticationRequest convert(HttpServletRequest request) {
        MultiValueMap<String, String> paramMap;
        if ("GET".equals(request.getMethod())) {
            paramMap = Tools.Http.getQueryParameters(request);
        } else if ("POST".equals(request.getMethod())) {
            paramMap = Tools.Http.getFormParameters(request);
        } else {
            return null;
        }
        String responseType = paramMap.getFirst(AuthenticationRequest.AuthenticationRequestFieldName.RESPONSE_TYPE);
        if (Tools.Str.isBlank(responseType) || !AuthenticationRequest.AuthenticationRequestFieldName.CODE.equals(responseType)) {
            return null;
        }
        String clientId = paramMap.getFirst(AuthenticationRequest.AuthenticationRequestFieldName.CLIENT_ID);
        if (Tools.Str.isBlank(responseType)) {
            return null;
        }
        String scope = paramMap.getFirst(AuthenticationRequest.AuthenticationRequestFieldName.SCOPE);
        if (Tools.Str.isBlank(scope) || !Tools.Str.split(scope).contains("openid")) {
            return null;
        }
        String redirectUri = paramMap.getFirst(AuthenticationRequest.AuthenticationRequestFieldName.REDIRECT_URI);
        if (Tools.Str.isBlank(redirectUri)) {
            return null;
        }
        String state = paramMap.getFirst(AuthenticationRequest.AuthenticationRequestFieldName.STATE);
        if (Tools.Str.isBlank(state)) {
            return null;
        }

        return AuthenticationRequest.generateAuthorizationCodeRequest(scope, clientId, state, redirectUri);
    }
}
